#include "../include/Thread.h"
#include <string.h>


namespace wd
{

Thread::Thread(ThreadCallback && cb)
: _pthid(0)
, _isRunning(false)
, _cb(std::move(cb))//参数cb是左值还是右值？左值
{}


void Thread::start()
{
    if(!_isRunning) {
        int ret = pthread_create(&_pthid, NULL, start_routine, this);
        if(ret != 0) {
            fprintf(stderr, "%s\n", strerror(ret));
            return;
        }
        //线程创建成功
        _isRunning = true;
    }
}
    
void Thread::join()
{
    if(_isRunning) {
        pthread_join(_pthid, NULL);
        _isRunning = false;
    }
}

//start_routine函数是一个静态成员函数
//静态成员内部不能直接调用非静态成员函数
//因为没有this指针
void * Thread::start_routine(void * arg) {
    //在该函数中调用run方法
    Thread * pthread = static_cast<Thread*>(arg);
    if(pthread) {
        pthread->_cb();
    }
    return NULL;
}


}//end of namespace wd
